package com.slipper.core.excel;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.style.column.AbstractColumnWidthStyleStrategy;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.ss.usermodel.Cell;

import java.util.List;

public class ColumnWidthStrategy  extends AbstractColumnWidthStyleStrategy {
   private final List<Integer> widthList;

    public ColumnWidthStrategy(List<Integer> widthList) {
        this.widthList = widthList;
    }

    protected void setColumnWidth(
            WriteSheetHolder writeSheetHolder,
            List<WriteCellData<?>> cellDataList,
            Cell cell,
            Head head,
            Integer relativeRowIndex,
            Boolean isHead) {
        boolean needSetWidth = isHead || !CollectionUtils.isEmpty(cellDataList);
        if (needSetWidth) {
            int columnWidth;
            if (cell.getColumnIndex() < widthList.size()) {
                columnWidth = widthList.get(cell.getColumnIndex()) * 2;
            } else {
                columnWidth = 15 * 2;
            }
            if (columnWidth >= 0) {
                if (columnWidth > 255) {
                    columnWidth = 255;
                }

                writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), columnWidth * 256);
            }
        }
    }
}